import string
import random

from django.contrib.auth.hashers import make_password
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from django.core.mail import send_mail

from app01.filter import check_login
from app01.forms import RegisterForm, LoginForm
from app01.models import User, EmailCaptcha
from app01.utils import md5
from django_project import settings


# # Create your views here.
# # def index(request):
# #     return HttpResponse("欢迎您来到django的世界!!!")
#
# def user_list(request):
#     #取app模流下的templetets文件下的user_list.html文件
#     #更具app的注册顺序，从app01开始找，找到就停止
#     return render(request,"user_list.html")
#
# def user_add(request):
#     return HttpResponse("用户添加")
#
# def tp(request):
#     name = "csskd"
#     roles = ["管理员","老板","程序员"]
#     user_info = {
#         "name":"csskd",
#         "age":18,
#         "sex":"男",
#         "role": "老板"
#     }
#     data_list = [
#         {"name":"csskd0","age":15,"sex":"男","role": "老板"},
#         {"name":"csskd1","age":28,"sex":"女","role": "管理员"},
#      ]
#
#     return render(request,"tp.html",{"n1":name,"n2":roles,"n3":user_info,"n4":data_list})
#
# def news(request):
#     url = "https://www.cuguplus.com/uplusApi/product/getProductSet"
#     import requests
#     res = requests.post(url)
#     data = res.json()
#     print(data)
#     return render(request,"news.html")
#
# def something(request):
#     # 1.请求的方法
#     print(request.method)
#
#     # 2.在URL上传递值 /something/?n1=123&n2=222 获取get请求的参数
#     print(request.GET)
#
#     # 3.在请求体中提交数据 获取post请求的参数
#     print(request.POST)
#     #print(request.body)
#
#     # 4.[响应] HttpResponse("返回内容")，内容字符串返回给请求
#     # return HttpResponse("返回内容")
#
#     # 5.[响应] 读取HTML的内容 + 渲染(替换) ->> 字符串，返回给用户浏览器
#     # return render(request,"something.html",{"title": "xxxxx"})
#
#     # 6.[响应] 让浏览器重定向到其他页面
#     return redirect("https://www.baidu.com")

@check_login
def index(request):
    return render(request,"auth/index.html")

def login(request):
    if request.method == "GET":
        return render(request,"auth/login.html")

    # 获取用户输入的邮箱和密码
    form = LoginForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password')
        user = User.objects.filter(email=email).first()
        print(f"插入密码加密:{make_password(password)}")
        print(f"保存的密码:{user.password}")
        if user and md5(password) == user.password:
            # cookie: 登录授权
            # flask 中的session，是经过加密后存储在cookie中
            request.session["user_id"] = user.id
            return redirect(reverse('app01:index'))
    print(form.errors)
    return redirect(reverse('app01:login'))

def register(request):
    form = RegisterForm()
    if request.method == "POST":
        # 验证码
        # 表单验证
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            password = md5(password)
            User.objects.create(email=email, username=username, password=password)
            return redirect(reverse('app01:login'))
    return render(request, "auth/register.html",context={"form": form})

    # print(form.errors)
    # # 重新跳转到登录页面
    # return redirect(reverse('app01:register'))
    # # return render(request, 'register.html', context={"form": form})

def logout(request):
    # session.pop("user_id")
    request.session.clear()
    return redirect(reverse("app01:index"))

def send_email_captcha(request):
    # ?email=xxx
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code": 400, "message": '必须传递邮箱！'})
    # 生成验证码（取随机的4位阿拉伯数字）
    # ['0', '2', '9', '8']
    captcha = "".join(random.sample(string.digits, 4))
    # 存储到数据库中
    EmailCaptcha.objects.update_or_create(email=email, defaults={'captcha': captcha})
    send_mail("app01注册验证码", message=f"您的注册验证码是：{captcha}", recipient_list=[email],from_email=None)
    # 将验证码存入到redis中
    cache.set(email, captcha, timeout=60)

    return JsonResponse({"code": 200, "message": "邮箱验证码发送成功！"})


def mail_test(request):
    captcha = "".join(random.sample(string.digits, 4))
    print(f"发送测试验证:【{captcha}】")
    send_mail("dG注册验证码", message=f"您的注册验证码是：{captcha}", recipient_list=['497716195@qq.com'], from_email= settings.DEFAULT_FROM_EMAIL)
    return HttpResponse("邮件发送成功")